package com.kehongborui.empmanagesys;

import com.kehongborui.entity.Emp;
import com.kehongborui.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-17
 */
@WebServlet(urlPatterns = {"/login", "/emp/list"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置session的超时时间
//        req.getSession().setMaxInactiveInterval(1);
        // 设置 req 字符集
        req.setCharacterEncoding("UTF-8");
        // 设置 resp 字符集以及文本格式
        resp.setContentType("text/html;charset=utf-8");

        // 获取打印流
        PrintWriter writer = resp.getWriter();
        // 从session 获取登录信息
        User user = (User) (req.getSession().getAttribute("loginUser"));
        if (user == null) {
            resp.sendRedirect("/");
            return;
        }
        // 登录成功，查询所有员工信息
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        List<Emp> empList = new ArrayList<>();
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/khbr_data_center", "root", "root");
            // 执行语句对象
            String findSql = "SELECT * FROM khbr_emp";
            statement = connection.prepareStatement(findSql);
            // 执行查询并处理结果集
            rs = statement.executeQuery();
            while (rs.next()) {
                // 创建用户对象
                Emp emp = new Emp();
                // 设置User对象的字段属性值
                emp.setName(rs.getString("name"));
                emp.setIdCardNo(rs.getString("idcard_no"));
                emp.setTel(rs.getString("tel"));

                empList.add(emp);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        writer.println("<h1>欢迎" + user.getUsername() + "登录</h1>");
        StringBuffer html = new StringBuffer("<table class=\"table table-striped\">\n" +
                "        <caption>员工列表</caption>\n" +
                "        <thead>\n" +
                "        <tr>\n" +
                "            <th>员工姓名</th>\n" +
                "            <th>身份证</th>\n" +
                "            <th>Tel</th>\n" +
                "        </tr>\n" +
                "        </thead>\n" +
                "        <tbody>\n");

        // 用 lambda 表达式 遍历 empList
        empList.stream().forEach(emp -> {
            html.append( "        <tr>\n" +
                    "            <td>" + emp.getName() +"</td>\n" +
                    "            <td>" + emp.getIdCardNo() + "</td>\n" +
                    "            <td>" + emp.getTel() + "</td>\n" +
                    "        </tr>\n");
        });



        html.append("        </tbody>\n" + "    </table>");
        writer.println(html.toString());
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置 req 字符集
        req.setCharacterEncoding("UTF-8");
        // 设置 resp 字符集以及文本格式
        resp.setContentType("text/html;charset=utf-8");

        // 获取 参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 获取连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/khbr_data_center", "root", "root");
            // 执行语句对象
            String findSql = "SELECT * FROM khbr_user WHERE username=? AND password=?";
            statement = connection.prepareStatement(findSql);
            statement.setString(1, username);
            statement.setString(2, password);
            // 执行查询并处理结果集
            rs = statement.executeQuery();
            if (rs.next()) {
                // 创建用户对象
                User user = new User();
                // 设置User对象的字段属性值
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRealName(rs.getString("real_name"));
                user.setIdCardNo(rs.getString("idcard_no"));
                // 登录成功，将用户信息放到 session 中
                req.getSession().setAttribute("loginUser", user);
                resp.sendRedirect("/emp/list");
            } else {
                resp.getWriter().println("<h1>登录失败："+username +"对应的信息不存在</h1>");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
